package com.aacar.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.aacar.constant.ConsFiled;
import com.aacar.dto.Header;
import com.aacar.dto.RegisterDto;
import com.aacar.dto.UserDto;
import com.aacar.entity.Member;
import com.aacar.entity.MobileHead;
import com.aacar.interceptor.MemLoginKeyValid;
import com.aacar.service.CheckCodeService;
import com.aacar.service.MemberService;
import com.aacar.service.MessageService;
import com.aacar.utils.ErrorCodeConsField;
import com.aacar.utils.ErrorInfoUtil;
import com.aacar.utils.Pphconfig;
import com.aacar.utils.RedisCacheManagerUtil;
import com.aacar.utils.ResultErrorInfo;
import com.aacar.utils.ResultInfoUtil;
import com.aacar.utils.SpringContextUtil;
import com.aacar.vo.CommonVo;
import com.aacar.vo.UserInfoVo;
import com.aacar.vo.UserVo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mysql.jdbc.StringUtils;

import java.util.Map;


@RestController
@RequestMapping("/member")
public class MemberController extends ValidController{
	private Logger logger = LoggerFactory.getLogger(this.getClass());
    
    @Resource
    private CheckCodeService checkCodeService;
    
    @Resource
    private MemberService memberService;
    
	@Autowired
	private  HttpServletRequest request;
	
	@Autowired
	private MessageService messageService;

	
    @RequestMapping(value = "/login/0", method = RequestMethod.POST)
    @ResponseBody
    public Object login(@RequestHeader(value="mobilehead") String mobilehead,@RequestBody UserDto userDto){
    	logger.info("request:/member/login/0" + JSONObject.toJSONString(userDto));
    	logger.info("requestHead:"+mobilehead);
    	Header header = null;
    	if(null != mobilehead) {
    		header = JSON.parseObject(mobilehead, Header.class);
    	}
    	if(null != header) {
    		return loginHandle(userDto,header.getService());
    	}
    	else
    		return loginHandle(userDto,null);
    }
    
    @RequestMapping(value = "/register/0", method = RequestMethod.POST)
    @ResponseBody
    public Object register(@RequestHeader(value="mobilehead") String mobilehead,@RequestBody RegisterDto registerDto){
		logger.info("request:/member/register/0" + JSONObject.toJSONString(registerDto));
		Header header = null;
		if(null != mobilehead) {
			header = JSON.parseObject(mobilehead, Header.class);
		}
		String phoneNo = registerDto.getPhoneNo();
		String code = registerDto.getCode();
		//1.校验
    	if(StringUtils.isNullOrEmpty(registerDto.getPassword()) || StringUtils.isNullOrEmpty(registerDto.getNewPassword())){
    		//登录密码不能为空
    		return ErrorInfoUtil.setErrorInfo(ErrorCodeConsField.ERROR_MSG_10201, Pphconfig.getContextProperty(ErrorCodeConsField.ERROR_MSG_10201),header.getService());
    	}
    	
    	if(StringUtils.isNullOrEmpty(registerDto.getPhoneNo())){
    		//手机号不能为空
    		return ErrorInfoUtil.setErrorInfo(ErrorCodeConsField.ERROR_MSG_10301, Pphconfig.getContextProperty(ErrorCodeConsField.ERROR_MSG_10301),header.getService());
    	}
    	//2.校验两次密码一样
    	if(!registerDto.getNewPassword().equals(registerDto.getNewPassword())) {
    		return ErrorInfoUtil.setErrorInfo(ErrorCodeConsField.ERROR_MSG_10307, Pphconfig.getContextProperty(ErrorCodeConsField.ERROR_MSG_10307),header.getService());
    	}
    	//2.手机号存在不在存在
    	CommonVo comv = this.memberService.getCountByPhoneNo(registerDto.getPhoneNo());
    	if(comv.isSuccess()) {//手机号已经注册了
    		return ErrorInfoUtil.setErrorInfo(ErrorCodeConsField.ERROR_MSG_10300, Pphconfig.getContextProperty(ErrorCodeConsField.ERROR_MSG_10300),header.getService());
    	}
    	//3.校验图片验证码
    	String result = this.messageService.validatorImageCode(phoneNo, code,ConsFiled.Code_Type_1);
    	if(null == result) {
    		return ErrorInfoUtil.setErrorInfo(ErrorCodeConsField.ERROR_MSG_10306, Pphconfig.getContextProperty(ErrorCodeConsField.ERROR_MSG_10306),header.getService());
    	}
    	//4.保存注册信息
    	CommonVo cv = memberService.saveMember(registerDto);
    	if(cv.isSuccess()) {
    		return ResultInfoUtil.setSuccessInfo(cv,header.getService());
    	}else {
    		return ErrorInfoUtil.setErrorInfo(ErrorCodeConsField.ERROR_MSG_10301, Pphconfig.getContextProperty(ErrorCodeConsField.ERROR_MSG_10301),header.getService());
    	}
		
    }
    
    @RequestMapping(value = "/forget_passwd/0", method = RequestMethod.POST)
    @ResponseBody
    public Object forgetPasswd(@RequestHeader(value="mobilehead") String mobilehead,@RequestBody Member member){
		logger.info("request:/member/forget_passwd/0" + JSONObject.toJSONString(member));
		Header header = null;
		if(null != mobilehead) {
			header = JSON.parseObject(mobilehead, Header.class);
		}
		if(StringUtils.isNullOrEmpty(member.getLoginName())){
			//登录名不能为空
    		return ErrorInfoUtil.setErrorInfo(ErrorCodeConsField.ERROR_MSG_10200, Pphconfig.getContextProperty(ErrorCodeConsField.ERROR_MSG_10200),header.getService());
    	}
    	if(StringUtils.isNullOrEmpty(member.getPassWord())){
    		//登录密码不能为空
    		return ErrorInfoUtil.setErrorInfo(ErrorCodeConsField.ERROR_MSG_10201, Pphconfig.getContextProperty(ErrorCodeConsField.ERROR_MSG_10201),header.getService());
    	}
    	
    	if(StringUtils.isNullOrEmpty(member.getMobile())){
    		//手机号不能为空
    		return ErrorInfoUtil.setErrorInfo(ErrorCodeConsField.ERROR_MSG_10301, Pphconfig.getContextProperty(ErrorCodeConsField.ERROR_MSG_10301),header.getService());
    	}
		

        //校验验证码
		Object result = checkCode(checkCodeService,member.getCheckCode(),member.getMobile(),"2");
		
		if(result instanceof ResultErrorInfo){
			return result;
		}
		
		/*if(!existMember(member)){
			//该账户不存在
			return ErrorInfoUtil.setErrorInfo(ErrorCodeConsField.ERROR_MSG_10304, Pphconfig.getContextProperty(ErrorCodeConsField.ERROR_MSG_10304));
		}*/
     	memberService.updateMember(member);
		
	    return ResultInfoUtil.setSuccessInfo(1);
    }
    
    @RequestMapping(value = "/modify_passwd/0", method = RequestMethod.POST)
    @ResponseBody
    @MemLoginKeyValid
    public Object modifyPasswd(@RequestHeader(value="mobilehead") String mobilehead,@RequestBody Member member){
		logger.info("request:/member/modify_passwd/0" + JSONObject.toJSONString(member));
		
		Header mobileHead = super.getMobileHead(request);
	    member.setMemberId(Long.valueOf(mobileHead.getUserId()));
	    Header header = null;
	    if(null != mobilehead) {
	    	header = JSON.parseObject(mobilehead, Header.class);
	    }
	    if(member.getMemberId()==0){
    		//会员ID不能为空
    		return ErrorInfoUtil.setErrorInfo(ErrorCodeConsField.ERROR_MSG_10304, Pphconfig.getContextProperty(ErrorCodeConsField.ERROR_MSG_10304),header.getService());
    	}
    	if(StringUtils.isNullOrEmpty(member.getPassWord())){
    		//旧登录密码不能为空
    		return ErrorInfoUtil.setErrorInfo(ErrorCodeConsField.ERROR_MSG_10302, Pphconfig.getContextProperty(ErrorCodeConsField.ERROR_MSG_10302),header.getService());
    	}
    	if(StringUtils.isNullOrEmpty(member.getPassWord())){
    		//新登录密码不能为空
    		return ErrorInfoUtil.setErrorInfo(ErrorCodeConsField.ERROR_MSG_10303, Pphconfig.getContextProperty(ErrorCodeConsField.ERROR_MSG_10303),header.getService());
    	}
	    return ResultInfoUtil.setSuccessInfo(1);
    }
    
    
    @RequestMapping(value = "/member_info/0", method = RequestMethod.POST)
    @ResponseBody
    @MemLoginKeyValid
    public Object getMemberInfo(@RequestBody Member member){
    	Header mobileHead = super.getMobileHead(request);
        member.setMemberId(Long.valueOf(mobileHead.getUserId()));
    	/*if(!existMember(member)){
    		//用户不存在
			return ErrorInfoUtil.setErrorInfo(ErrorCodeConsField.ERROR_MSG_10207, Pphconfig.getContextProperty(ErrorCodeConsField.ERROR_MSG_10207));
    	}*/
    	return null;
    }
    
    
    /**
     * 修改用户信息
     * @param member
     * @return
     */
    @RequestMapping(value = "/update_member/0", method = RequestMethod.POST)
    @ResponseBody
//    @MemLoginKeyValid
    public Object updateMember(@RequestBody Member member){
    	logger.info("request:/member/update_member/0" + JSONObject.toJSONString(member));
    	Header mobileHead = super.getMobileHead(request);
        member.setMemberId(Long.valueOf(mobileHead.getUserId()));
    	int result = memberService.updateMember(member);
    	if(result > 0) {
    		return ResultInfoUtil.setSuccessInfo(result,mobileHead.getService());
    	}else {
    		return ErrorInfoUtil.setErrorInfo(ErrorCodeConsField.ERROR_MSG_10309, Pphconfig.getContextProperty(ErrorCodeConsField.ERROR_MSG_10309),mobileHead.getService());
    	}
    }
    
   
    /**
     * 手机号号是否存在
     */
    @RequestMapping(value = "/is_exist_phoneNo/0", method = RequestMethod.POST)
    @ResponseBody
    public Object existMember(@RequestHeader(value="mobilehead") String mobilehead,@RequestBody UserDto userDto) {
    	logger.info("request:/member/exist/0" + JSONObject.toJSONString(userDto));
    	CommonVo cv = this.memberService.getCountByPhoneNo(userDto.getPhoneNo());
    	Header header = null;
    	if(null != mobilehead) {
    		header = JSON.parseObject(mobilehead, Header.class);
    	}
    	if(cv.isSuccess()) {
    		return ResultInfoUtil.setSuccessInfo(cv);
    	}
    	else {
    		return ErrorInfoUtil.setErrorInfo(ErrorCodeConsField.ERROR_MSG_10300, Pphconfig.getContextProperty(ErrorCodeConsField.ERROR_MSG_10300),header.getService());
    	}
  	}
    
    private Object loginHandle(UserDto userDto,String serviceCode) {
    	if(StringUtils.isNullOrEmpty(userDto.getPhoneNo())){
    		return ErrorInfoUtil.setErrorInfo(ErrorCodeConsField.ERROR_MSG_10200, Pphconfig.getContextProperty(ErrorCodeConsField.ERROR_MSG_10200),serviceCode);
    	}
    	if(StringUtils.isNullOrEmpty(userDto.getPassWord())){
    		return ErrorInfoUtil.setErrorInfo(ErrorCodeConsField.ERROR_MSG_10201, Pphconfig.getContextProperty(ErrorCodeConsField.ERROR_MSG_10201),serviceCode);
    	}
    	
    	UserVo userInfo = memberService.getMember(userDto);
    	if (userInfo == null) {
    		//账户不存在
    		return ErrorInfoUtil.setErrorInfo(ErrorCodeConsField.ERROR_MSG_10202, Pphconfig.getContextProperty(ErrorCodeConsField.ERROR_MSG_10202),serviceCode);
        }else if(! userInfo.getPassWord().equals(userDto.getPassWord())) {
        	return ErrorInfoUtil.setErrorInfo(ErrorCodeConsField.ERROR_MSG_10203, Pphconfig.getContextProperty(ErrorCodeConsField.ERROR_MSG_10203),serviceCode);
        }
		return ResultInfoUtil.setSuccessInfo(userInfo,serviceCode);
	}
    
    //获取个人信息
    @RequestMapping(value = "/getPersonalInfo/0", method = RequestMethod.POST)
    @ResponseBody
    @MemLoginKeyValid
    public Object getPersonalInfo(@RequestBody UserDto userDto) {
    	UserInfoVo uiv = this.memberService.getUserInfo(userDto);
    	return ResultInfoUtil.setSuccessInfo(uiv);
    }
    
    //退出登录
    @RequestMapping(value = "/loginOut/0", method = RequestMethod.POST)
    @ResponseBody
    @MemLoginKeyValid
    public Object loginOut(HttpServletRequest req) {
    	RedisCacheManagerUtil tokenCache = (RedisCacheManagerUtil) SpringContextUtil.getBean(ConsFiled.REDIE_CACHE);
    	String header = req.getHeader(ConsFiled.Request_Header);//获取请求头
    	Header hd = null;
    	if(null != header) {
    		hd = JSON.parseObject(header, Header.class);
    		tokenCache.del(hd.getToken());
    	}
    	CommonVo cmv = new CommonVo();
    	cmv.setSuccess(true);
    	cmv.setInfo(ConsFiled.LoginOut_SUCCESS_INFO);
    	return ResultInfoUtil.setSuccessInfo(cmv,hd.getService());
    }
    
    //修改密码
    @RequestMapping(value = "/updatePersonalInfo/0", method = RequestMethod.POST)
    @ResponseBody
    @MemLoginKeyValid
    public Object updatePersonalInfo(@RequestHeader(value="mobilehead") String mobilehead,@RequestBody UserDto userDto) {
    	Header header = null;
    	if(null != mobilehead) {
    		header = JSON.parseObject(mobilehead, Header.class);
    	}
    	if(!userDto.getConfirmPassword().equals(userDto.getNewPassword())) {
    		return ErrorInfoUtil.setErrorInfo(ErrorCodeConsField.ERROR_MSG_10209, Pphconfig.getContextProperty(ErrorCodeConsField.ERROR_MSG_10209),header.getService());
    	}
    	userDto.setUserId(Long.parseLong(header.getUserId()));
    	//确认密码不一致
    	UserInfoVo info = this.memberService.getUserInfo(userDto);
    	if(null == info) {
    		return ErrorInfoUtil.setErrorInfo(ErrorCodeConsField.ERROR_MSG_10206, Pphconfig.getContextProperty(ErrorCodeConsField.ERROR_MSG_10206),header.getService());
    	}
    	CommonVo cmv = this.memberService.updateUserInfo(userDto);
    	return ResultInfoUtil.setSuccessInfo(cmv,header.getService());
    }
    
    //重置密码
    @RequestMapping(value = "/reset_passwd/0", method = RequestMethod.POST)
    @ResponseBody
    public Object resetPasswd(@RequestHeader(value="mobilehead") String mobilehead,@RequestBody RegisterDto registerDto) {
    	logger.info("request:/member/reset_passwd/0" + JSONObject.toJSONString(registerDto));
		Header header = null;
		if(null != mobilehead) {
			header = JSON.parseObject(mobilehead, Header.class);
		}
		String phoneNo = registerDto.getPhoneNo();
		String code = registerDto.getCode();
		//1.校验
    	if(StringUtils.isNullOrEmpty(registerDto.getPassword()) || StringUtils.isNullOrEmpty(registerDto.getNewPassword())){
    		//登录密码不能为空
    		return ErrorInfoUtil.setErrorInfo(ErrorCodeConsField.ERROR_MSG_10201, Pphconfig.getContextProperty(ErrorCodeConsField.ERROR_MSG_10201),header.getService());
    	}
    	
    	if(StringUtils.isNullOrEmpty(registerDto.getPhoneNo())){
    		//手机号不能为空
    		return ErrorInfoUtil.setErrorInfo(ErrorCodeConsField.ERROR_MSG_10301, Pphconfig.getContextProperty(ErrorCodeConsField.ERROR_MSG_10301),header.getService());
    	}
    	//2.手机号存在不在存在
//    	CommonVo comv = this.memberService.getCountByPhoneNo(registerDto.getPhoneNo());
//    	if(!comv.isSuccess()) {//手机号已经注册了
//    		return ErrorInfoUtil.setErrorInfo(ErrorCodeConsField.ERROR_MSG_10300, Pphconfig.getContextProperty(ErrorCodeConsField.ERROR_MSG_10300));
//    	}
    	//3.校验图片验证码
    	String result = this.messageService.validatorImageCode(ConsFiled.Code_Type_2,phoneNo, code);
    	if(null == result && !"".equals(result)) {
    		return ErrorInfoUtil.setErrorInfo(ErrorCodeConsField.ERROR_MSG_10306, Pphconfig.getContextProperty(ErrorCodeConsField.ERROR_MSG_10306),header.getService());
    	}
    	//4.更新密码
    	UserDto userDto = new UserDto();
    	userDto.setPhoneNo(phoneNo);
    	userDto.setPassWord(registerDto.getPassword());
    	CommonVo cv = memberService.updateUserInfo(userDto);
    	if(cv.isSuccess()) {
    		return ResultInfoUtil.setSuccessInfo(cv,header.getService());
    	}else {
    		return ErrorInfoUtil.setErrorInfo(ErrorCodeConsField.ERROR_MSG_10301, Pphconfig.getContextProperty(ErrorCodeConsField.ERROR_MSG_10301),header.getService());
    	}
    	
    }

	//更新devicetokens
	@RequestMapping(value = "/update_devicetokens/0", method = RequestMethod.POST)
	@ResponseBody
	@MemLoginKeyValid
	public Object updateDeviceTokens(@RequestHeader(value="mobilehead") String mobilehead,@RequestBody Map map) {
		Header mobileHead = super.getMobileHead(request);
		logger.info("request:/member/update_devicetokens/0" + JSONObject.toJSONString(map));
		Member member = new Member();
		member.setMemberId(Long.valueOf(mobileHead.getUserId()));
		member.setDeviceTokens(String.valueOf(map.get("deviceTokens")));
		member.setDeviceType(mobileHead.getDeviceType());
		int res = this.memberService.updateMember(member);
		return ResultInfoUtil.setSuccessInfo(res,mobileHead.getService());
	}
    
}
